package lt.ntec.danblog.server.core.model.gae;

import java.util.Date;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import lt.ntec.danblog.server.core.model.User;
import com.google.appengine.api.datastore.Key;
import com.google.inject.Inject;

@PersistenceCapable
class JDOUser implements User {

    @Persistent(defaultFetchGroup = "true")
    private com.google.appengine.api.users.User sysUser;
    @Persistent
    private Date lastAccessDate;
    @Persistent
    private String email;
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Inject
    public JDOUser(com.google.appengine.api.users.User user) {
        this.sysUser = user;
        this.email = user.getEmail();
    }

    public com.google.appengine.api.users.User getSysUser() {
        return sysUser;
    }

    @Override
    public void setLastAccessDate(Date date) {
        lastAccessDate = date;
    }

    @Override
    public String getName() {
        if (this.sysUser == null) {
            return "Null";
        }
        return this.sysUser.getNickname();
    }

    @Override
    public String getEmail() {
        return email;
    }

    @Override
    public Long getId() {
        if (key == null) {
            return null;
        }
        return key.getId();
    }

    @Override
    public Date getLastAccessDate() {
        return lastAccessDate;
    }

    @Override
    public boolean isRegistered() {
        return (sysUser != null);
    }

    @Override
    public boolean isAdmin() {
        // TODO
        throw new RuntimeException("stub");
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof JDOUser)) {
            return false;
        }
        JDOUser user = (JDOUser) o;
        if (user.getId() != this.getId()) {
            return false;
        }
        return true;
    }
}
